import React, {useState, useEffect } from "react";
import axios from 'axios';
import { Layout, Menu, Form, Input, Button, Upload, message } from 'antd';
import { Table, Divider } from 'antd';
import AdminStyles from './admin.module.css';


const { Header, Content, Sider } = Layout;







const Admin = () => {

  const [loginFlag, setLoginFlag] = useState(true);
  const [menuKey, setMenuKey] = useState('1');
  const [babyData, setBabyData] = useState([]);
  const [shapeData, setShapeData] = useState([]);
  const [brandData, setBrandData] = useState([]);
  const [classTabData, setclassTabData] = useState([]);
  const [classContentData, setclassContentData] = useState([]);
  const [userData, setUserData] = useState([]);



  // 页面初始化请求数据，判断是否登录
  const initData = async () => {
    const isLoginRes = (await axios({
      method: 'post',
      url: 'http://zhuyp.ccimm.top/api/isLogin',
    })).data;

    // 未登录 跳转到登录页
    if (isLoginRes.code === 12) {
      setLoginFlag(false);
      window.location.href = 'http://zhuyp.ccimm.top/login';
    } else {
      setLoginFlag(true);
    }
  };


  // 接口请求数据，回填到Form表单初始值
  const getBabyData = async () => {
    const babyRes = (await axios.get(`/api/baby`)).data;
    setBabyData(babyRes);
  };

  const getShapeData = async () => {
    const shapeRes = (await axios.get(`/api/shape`)).data;
    setShapeData(shapeRes);
  };

  const getBrandData = async () => {
    const brandRes = (await axios.get(`/api/brandContent`)).data;
    setBrandData(brandRes);
  };

  const getClassData = async () => {
    const classTabRes = (await axios.get(`/api/tabTitle`)).data;
    const classContentRes = (await axios.get(`/api/tabContent`)).data;
    setclassTabData(classTabRes);
    setclassContentData(classContentRes);
  };
  const getUserData = async () => {
    const userRes = (await axios.get(`/api/contentUser?type=all`)).data;
    setUserData(userRes);
  };

  const { Column, ColumnGroup } = Table;





  useEffect(() => {
    initData();
  }, []);

  useEffect(() => {
    getBabyData();
    getShapeData();
    getBrandData();
    getClassData();
    getUserData();
  }, loginFlag);



  return <>
    {
      loginFlag ? <Layout>
        <Sider
          breakpoint="lg"
          collapsedWidth="0"
        >
          <div className="logo" />
          <Menu theme="dark" mode="inline" onClick={(e) => {
            const value = e.key;
            setMenuKey(value);
          }} defaultSelectedKeys={['1']}>
            <Menu.Item key="1">
              <span className="nav-text">首页</span>
            </Menu.Item>
            <Menu.Item key="2">
              <span className="nav-text">品牌</span>
            </Menu.Item>
            <Menu.Item key="3">
              <span className="nav-text">课程</span>
            </Menu.Item>
            <Menu.Item key="4">
              <span className="nav-text">预约用户</span>
            </Menu.Item>
          </Menu>
        </Sider>
        <Layout>
          <Header style={{ background: '#fff', padding: 0 }} />
          <Content style={{ padding: '24px 16px 0', backgroundColor: '#fff' }}>
            {
              (() => {
                switch (menuKey) {
                  case '1':
                    return babyData.length === 0 || shapeData.length === 0? <></> : <div>
                      <h1>教育机构</h1>
                      {
                        babyData.map((item, index) => {
                          return <Form layout="inline">
                            <Form.Item label={'标题'}>
                              <Input
                                value={babyData[index].title}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setBabyData(prevState => {
                                    prevState[index].title = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="title"
                              />
                            </Form.Item>
                            <Form.Item label={'内容'}>
                              <Input
                                value={babyData[index].content}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setBabyData(prevState => {
                                    prevState[index].content = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="content"
                              />
                            </Form.Item>
                            <Form.Item label={'标题图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setBabyData(prevState => {
                                      prevState[index].headImg = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item label={'内容图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setBabyData(prevState => {
                                      prevState[index].decImg = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item>
                              <Button type='primary' onClick={async () => {
                                const updateRes = (await axios.post('/api/admin/modBaby', babyData[index])).data;
                                if (updateRes.code === 0) {
                                  message.success('更新成功');
                                }else {
                                  message.error('更新失败');
                                }
                              }}>确认</Button>
                            </Form.Item>
                          </Form>
                        })
                      }
                      <h1>教育系统</h1>
                      {
                        shapeData.map((item,index) => {
                          return <Form layout="inline">
                            <Form.Item label={'标题'}>
                              <Input
                                value={shapeData[index].title}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setShapeData(prevState => {
                                    prevState[index].title = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="title"
                              />
                            </Form.Item>
                            <Form.Item label={'内容'}>
                              <Input
                                value={shapeData[index].content}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setShapeData(prevState => {
                                    prevState[index].content = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="content"
                              />
                            </Form.Item>
                            <Form.Item label={'内容图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setShapeData(prevState => {
                                      prevState[index].img = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item>
                              <Button type='primary' onClick={async () => {
                                const updateRes = (await axios.post('/api/admin/modShape', shapeData[index])).data;
                                if (updateRes.code === 0) {
                                  message.success('更新成功');
                                }else {
                                  message.error('更新失败');
                                }
                              }}>确认</Button>
                            </Form.Item>
                          </Form>
                        })
                      }
                    </div>;
                  case '2':
                    return brandData.length === 0 ? <></> : <div>
                      <h1>品牌介绍</h1>
                      {
                        brandData.map((item, index) => {
                          return <Form layout="inline">
                            <Form.Item label={'标题'}>
                              <Input
                                value={brandData[index].tiTle}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setBrandData(prevState => {
                                    prevState[index].tiTle = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="title"
                              />
                            </Form.Item>
                            <Form.Item label={'文本'}>
                              <Input
                                value={brandData[index].text}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setBrandData(prevState => {
                                    prevState[index].content = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="content"
                              />
                            </Form.Item>
                            <Form.Item label={'主图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setBrandData(prevState => {
                                      prevState[index].banner = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item label={'左图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setBrandData(prevState => {
                                      prevState[index].imgRight = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item label={'右图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setBrandData(prevState => {
                                      prevState[index].imgRight = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item>
                              <Button type='primary' onClick={async () => {
                                const updateRes = (await axios.post('/api/admin/modBrand', brandData[index])).data;
                                if (updateRes.code === 0) {
                                  message.success('更新成功');
                                }else {
                                  message.error('更新失败');
                                }
                              }}>确认</Button>
                            </Form.Item>
                          </Form>
                        })
                      }
                    </div>;
                  case '3':
                    return classTabData.length === 0 || classContentData.length === 0 ? <></> : <div>
                      <h1>课程分类</h1>
                      {
                        classTabData.map((item, index) => {
                          return <Form layout="inline">
                            <Form.Item label={'中文名称'}>
                              <Input
                                value={classTabData[index].cnName}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setBrandData(prevState => {
                                    prevState[index].cnName = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="中文名称"
                              />
                            </Form.Item>
                            <Form.Item label={'英文名称'}>
                              <Input
                                value={classTabData[index].enName}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setclassTabData(prevState => {
                                    prevState[index].enName = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="英文名称"
                              />
                            </Form.Item>
                            <Form.Item>
                              <Button type='primary' onClick={async () => {
                                const updateRes = (await axios.post('/api/admin/modTabTitle', classTabData[index])).data;
                                if (updateRes.code === 0) {
                                  message.success('更新成功');
                                }else {
                                  message.error('更新失败');
                                }
                              }}>确认</Button>
                            </Form.Item>
                          </Form>
                        })
                      }
                      <h1>详细介绍</h1>
                      {
                        classContentData.map((item, index) => {
                          return <Form layout="inline">
                            <Form.Item label={'标题'}>
                              <Input
                                value={classContentData[index].tabTop}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setclassContentData(prevState => {
                                    prevState[index].tabTop = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="title"
                              />
                            </Form.Item>
                            <Form.Item label={'文本'}>
                              <Input
                                value={classContentData[index].tabText}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setclassContentData(prevState => {
                                    prevState[index].tabText = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="content"
                              />
                            </Form.Item>
                            <Form.Item label={'详情'}>
                              <Input
                                value={classContentData[index].tabLeftb}
                                onChange={(e) => {
                                  const value = e.target.value;
                                  setclassContentData(prevState => {
                                    prevState[index].tabLeftb = value;
                                    return [...prevState];
                                  })
                                }}
                                placeholder="content"
                              />
                            </Form.Item>
                            <Form.Item label={'图标'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setclassContentData(prevState => {
                                      prevState[index].ico = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item label={'左图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setclassContentData(prevState => {
                                      prevState[index].tabLefta = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item label={'右图片'}>
                              <Upload {...{
                                type: 'file',
                                action: '/api/upload',
                                onChange: (data) => {
                                  const { file } = data;
                                  if (file.status === 'done') {
                                    setclassContentData(prevState => {
                                      prevState[index].tabRight = file.response.data.filename;
                                      return [...prevState];
                                    })
                                  }
                                }
                              }}>
                                <Button>
                                  上传图片
                                </Button>
                              </Upload>
                            </Form.Item>
                            <Form.Item>
                              <Button type='primary' onClick={async () => {
                                const updateRes = (await axios.post('/api/admin/modTabContent', classContentData[index])).data;
                                if (updateRes.code === 0) {
                                  message.success('更新成功');
                                }else {
                                  message.error('更新失败');
                                }
                              }}>确认</Button>
                            </Form.Item>
                          </Form>
                        })
                      }
                    </div>;
                  case '4':
                    return userData.length ===0 ?<></> : <div>
                      <h1>用户管理</h1>
                      <Table dataSource={userData} pagination={false}>
                        <Column title="宝宝昵称" dataIndex="name" />
                        <Column title="宝宝生日" dataIndex="birthday" />
                        <Column title="家长电话" dataIndex="telphone" />
                        <Column title="地址" dataIndex="address" />
                        <Column
                            title={'操作'}
                            key={'action'}
                            render={(value) => {
                              return (
                                  <span>
                                    {
                                      value.type !== 1 && (<><a onClick={async () => {
                                        const accessData = (await axios.get(`/api/admin/user/access?id=${value._id}`)).data;
                                        if (accessData.code === 0) {
                                          message.success('审核通过成功');
                                          getUserData();
                                        } else {
                                          message.error('未知错误');
                                        }
                                      }}>审核通过</a><Divider type="vertical" /></>)
                                    }

                                    <a
                                        onClick={async () => {
                                          const deleteData = (await axios.get(`/api/admin/user/delete?id=${value._id}`)).data;
                                          if (deleteData.code === 0) {
                                            message.success('删除成功');
                                            getUserData();
                                          } else {
                                            message.error('未知错误');
                                          }
                                        }}
                                    >删除</a>
                                  </span>
                              )
                            }}
                            />
                        >
                      </Table>
                    </div>
                }
              })()
            }
          </Content>
        </Layout>
      </Layout>: <></>
    }
  </>
};

export default Admin;
